# Figure 1

#set the working directory here
setwd("")

# load the IGO membership array:
load("membership-expanded3.rda")

# load the communities data:
load("clubs of clubs data 2.rda")

# load the IGO statistics:
load("igostats5.rda")


### 1. Show changes in the median number of IGOs to which states belong each year:

yearlist<-as.character(c(1945, 1950, 1955, 1960, 1965, 1966:2005))
membershipstats<-matrix(NA, nrow=11, ncol=length(yearlist), dimnames=list(seq(0,1, 0.1), yearlist))
for (y in yearlist){
	membership.current<-membership[membership[,"UN",y]==1, , y]
	totals.current<-rowSums(membership.current)
	membershipstats[,y]<-quantile(totals.current, seq(0,1, 0.1))
	}

pdf("Figure 1.pdf", width=14, height=7)
par(mfrow=c(1,2))
plot(yearlist, yearlist, type="n", lwd=3, bty="n", las=1, ylab="Number of IGO Memberships", xlab="Year", ylim=c(0, 130), main="Number of IGOs to which States Belong")
label<-c("Minimum", "1st Decile", "2nd Decile", "3rd Decile", "4th Decile", "Median", "6th Decile", "7th Decile", "8th Decile", "9th Decile", "Maximum")
#polygon(c(yearlist, rev(yearlist)), c(membershipstats["Q1",], rev(membershipstats["Q3",])), col="grey80", border=NA)
for (i in 1:nrow(membershipstats)){ 
	lines(yearlist, membershipstats[i,], col="grey80")
	text(as.numeric(yearlist[i*2]), membershipstats[i,yearlist[i*2]], label[i], col="grey80", cex=0.8)
	}
lines(yearlist, membershipstats["0.5",], lwd=3)


### 2. Calculate the median size of IGOs (in terms of their number of members) over time:
yearlist<-as.character(c(1945, 1950, 1955, 1960, 1965, 1966:2005))
IGOsize<-apply(membership, c(2,3), sum)
sizestats<-matrix(NA, nrow=11, ncol=length(yearlist), dimnames=list(seq(0,1, 0.1), yearlist))
for (y in yearlist){
	activeIGOs<-names(which(IGOsize[,y]>0))
	sizestats[,y]<-quantile(IGOsize[activeIGOs, y], seq(0,1,0.1))
	}
plot(yearlist, yearlist, type="n", lwd=3, bty="n", las=1, ylab="Number of Member States", xlab="Year", ylim=c(0,200), main="Number of Member States of IGOs")
label<-c("Minimum", "1st Decile", "2nd Decile", "3rd Decile", "4th Decile", "Median", "6th Decile", "7th Decile", "8th Decile", "9th Decile", "Maximum")
for (i in 1:nrow(sizestats)){ 
	lines(yearlist, sizestats[i,], col="grey80")
	text(as.numeric(yearlist[i*2]), sizestats[i,yearlist[i*2]], label[i], col="grey80", cex=0.8)
	}
lines(yearlist, sizestats["0.5",], lwd=3)
dev.off()

sizestats["0.5",] # look at the medians over time
sizestats["0.8",] # look at the 8th decile over time

